package com.yzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yzy.domain.entity.system.RoleTypeEnum;
import com.yzy.domain.entity.system.Role;
import com.yzy.exception.VisionException;
import com.yzy.mapper.system.RoleMapper;
import com.yzy.service.RoleService;
import com.yzy.util.GlobalBeanUtils;
import com.yzy.domain.vo.system.RoleVO;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Role save(Role role) {
        roleMapper.insert(role);
        return role;
    }

    @Override
    public List<RoleVO> list(String name) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(name),Role::getName, name);
        wrapper.orderByDesc(Role::getCreatedOn);
        List<Role> roles = roleMapper.selectList(wrapper);
        return GlobalBeanUtils.copyListProperties(roles, RoleVO::new);
    }

    @Override
    public Role save(String name, String accountId) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getName, name);
        if (null != roleMapper.selectOne(wrapper)) {
            throw new VisionException(HttpStatus.INTERNAL_SERVER_ERROR, "角色名称重复！！！");
        }

        Role role = new Role();
        role.setName(name);
        role.setCreatedBy(accountId);
        role.setIsDefault(false);
        role.setType(RoleTypeEnum.CUSTOM);
        roleMapper.insert(role);
        return role;
    }

    @Override
    public void update(String roleId, String name, String accountId) {
        //如果是三个默认角色，则不允许编辑
        Role role = findByRoleId(roleId);
        role.setName(name);
        role.setUpdatedBy(accountId);
        roleMapper.updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String roleId, String accountId) {
        //如果是三个默认角色，则不允许删除
        Role byRoleId = findByRoleId(roleId);
        roleMapper.deleteById(roleId);
    }

    @Override
    public Role findByAccountId(String accountId) {
        return Optional.ofNullable(roleMapper.findByAccountId(accountId)).orElseThrow(
                () -> new VisionException(HttpStatus.NOT_FOUND, "角色不存在，请重试！")
        );
    }

    @Override
    public Role findByRoleId(String roleId) {
        return Optional.ofNullable(roleMapper.selectById(roleId)).orElseThrow(
                () -> new VisionException(HttpStatus.NOT_FOUND, "角色不存在，请重试！")
        );
    }
}
